package com.linewell.util;

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


/**
 * mongodb 升降序
 */
public class SortModelUtils {

	public static Direction getMongodbDirection(int x){
		
		switch(x){
		case 0:
			return Direction.ASC;
		case 1:
			return Direction.DESC;
		}
		return null;
	}
	
	public static Sort getMongodbSort(Integer[] sort, String[] fields, Class cls){
		
		List<Order> orders = new ArrayList();
		for(int i=0;i<fields.length;i++){
			
			Field field = null;
			try {
				field = cls.getDeclaredField(fields[i]);
			} catch (NoSuchFieldException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			org.springframework.data.mongodb.core.mapping.Field f = field.getAnnotation(org.springframework.data.mongodb.core.mapping.Field.class);
			
			
			Direction d = SortModelUtils.getMongodbDirection(sort[i]);
			orders.add(new Order(d,f.value()));
		}
		
		return new Sort(orders);
	}
	
	public static void main(String[] args){
		
//		System.out.println(Direction.DESC.ordinal());
	}
}
